import subprocess

from appium import webdriver
from time import sleep
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

desired_caps = {
    "platformName": "Android",
    "automationName": "uiautomator2",
    "platformVersion": "9",
    "deviceName": '192.168.2.241:5555',
    "appPackage": "com.seven.qaml.burstserven",
    "appActivity": "com.seven.qaml.burstserven.ui.MainActivity",
    'skipServerInstallation': False,
    'skipDeviceInitialization': False,
    "noReset": True
}
appium_server_url = 'http://127.0.0.1:4723'
driver = webdriver.Remote(appium_server_url, desired_caps)

sleep(3)
num = 1
menu_id = "com.seven.qaml.burstserven:id/tv_F1"
version_id = "com.seven.qaml.burstserven:id/text_ver"


def get_app_memory_usage(package_name):
    try:
        # 执行ADB命令获取应用内存使用信息
        result = subprocess.check_output(['adb', 'shell', 'dumpsys', 'meminfo', package_name])
        # 解析命令输出，查找包含TOTAL关键词的行，但排除TOTAL PSS关键词的行
        lines = result.decode('utf-8').splitlines()
        for line in lines:
            if 'TOTAL' in line and 'TOTAL PSS' not in line:
                # 提取内存使用量（单位为KB）
                mem_kb = int(line.split()[1])
                # 将内存使用量转换为MB并返回
                return mem_kb / 1024
        # 如果未找到符合条件的行，返回None
        return None
    except Exception as e:
        # 异常处理：打印错误信息并返回None
        print(f"获取内存信息失败: {e}")
        return None


while num < 501:
    # 进入主菜单
    driver.keyevent(66)
    WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.ID, menu_id))
    )
    # 进入注册
    driver.keyevent(9)
    sleep(2)
    # 返回主菜单
    driver.keyevent(4)
    WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.ID, menu_id))
    )
    # 返回首页
    driver.keyevent(4)
    WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.ID, version_id))
    )
    print(f"已执行 {num} 次")

    used_memory_mb = get_app_memory_usage("com.seven.qaml.burstserven")
    if used_memory_mb is not None:
        print(f"APP 内存占用: {used_memory_mb:.2f} MB")
    else:
        print("无法获取内存信息")

    num += 1
